package org.infodavid.common.impl.services.security;

import java.util.regex.Pattern;

import org.infodavid.common.model.IUser;
import org.infodavid.common.services.exceptions.ServiceException;

/**
 * The Class RegexPasswordPolicy.
 */
public class RegexPasswordPolicy extends DefaultPasswordPolicy {

	/** The pattern. */
	private final Pattern pattern;

	/**
	 * The Constructor.
	 */
	public RegexPasswordPolicy() {
		super();

		pattern = null;
	}

	/**
	 * The Constructor.
	 * @param regex the regex
	 */
	public RegexPasswordPolicy(final String regex) {
		super();

		pattern = regex == null ? null : Pattern.compile(regex);
	}

	/**
	 * The Constructor.
	 * @param min the min
	 * @param max the max
	 * @param regex the regex
	 */
	public RegexPasswordPolicy(final int min, final int max, final Pattern regex) {
		super(min, max);

		pattern = regex;
	}

	/**
	 * The Constructor.
	 * @param min the min
	 * @param max the max
	 * @param regex the regex
	 */
	public RegexPasswordPolicy(final int min, final int max, final String regex) {
		super(min, max);

		pattern = regex == null ? null : Pattern.compile(regex);
	}

	/*
	 * See super class or interface. (non-Javadoc)
	 * @see org.infodavid.common.impl.services.security.DefaultPasswordPolicy#validate(long,
	 * java.lang.String)
	 */
	@Override
	public void validate(final long userkey, final String password) throws ServiceException {
		super.validate(userkey, password);

		if (!pattern.matcher(password).matches()) {
			throw new IllegalArgumentException(IUser.PASSWORD + ':' + password);
		}
	}
}
